package base

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/vueadmin/app/admin/internal/dto"
	"github.com/vueadmin/app/admin/internal/model"
	"github.com/vueadmin/app/admin/internal/service"
	"github.com/vueadmin/app/admin/internal/svc"
	"github.com/vueadmin/pkg/cache"
	"github.com/vueadmin/utils"
	"github.com/vueadmin/utils/common/result"
	"github.com/vueadmin/utils/conv"
	"github.com/vueadmin/utils/response"
	"net/http"
	"sort"
)

func GetSiteInfo(c *gin.Context, svcCtx *svc.ServiceContext) {
	data := make(map[string]interface{})
	data["site_title"] = c.Value("site_title")
	data["logo"] = c.Value("logo")
	data["role_id"] = c.Value("role_id")
	data["user"] = c.Value("user")

	access := conv.Slice(c.Value("access"))

	s := service.NewBaseService(svcCtx)
	menu := s.GetMenu(conv.Uint(data["role_id"]), access)
	baseComponents := s.GetComponents(conv.Uint(data["role_id"]), menu)
	hiddenComponents := s.GetHiddenComponents(conv.Uint(data["role_id"]), access)

	for _, v := range hiddenComponents {
		baseComponents = append(baseComponents, v)
	}
	c.JSON(http.StatusOK, result.M{
		"status":     http.StatusOK,
		"menu":       menu,
		"data":       data,
		"components": baseComponents,
		"actions":    access,
	})
}

// 获取权限节点
func GetRoleMenus(c *gin.Context, svcCtx *svc.ServiceContext) {
	s := service.NewBaseService(svcCtx)
	data, err := s.GetRoleMenu()
	if err != nil {
		response.Err(c, err)
		return
	}
	secondNodes := []*model.Menu{
		{
			Title:  "基础操作",
			Access: "/admin/Base",
			Sortid: 1,
			Children: []*model.Menu{
				{
					Title:  "重置密码",
					Access: "/admin/Base/resetPwd",
				},
			},
		},
	}
	for _, v := range secondNodes {
		data = append(data, v)
	}

	sort.Slice(data, func(i, j int) bool {
		return data[i].Sortid < data[j].Sortid
	})

	response.Success(c, "success", data)
}

// 重置密码
func ResetPwd(c *gin.Context, svcCtx *svc.ServiceContext) {
	req := dto.ResetPwdReq{}
	if err := utils.BindAndValid(c, &req); err != nil {
		response.Fail(c, err.Error())
		return
	}
	s := service.NewBaseService(svcCtx)
	if err := s.ResetPwd(&req, c.Value("user_id")); err != nil {
		response.Err(c, err)
		return
	}
	response.Success(c, "重置成功", nil)
}

// 清除内存缓存
func ClearCache(c *gin.Context, svcCtx *svc.ServiceContext) {
	cache.New(svcCtx.Redis).Delete(c.Request.Host + "/base_config")
	response.Success(c, "操作成功", nil)
}

// 获取省市区数据
func GetShenshiqu(c *gin.Context, svcCtx *svc.ServiceContext) {
	req := dto.Shenshiqu{}
	if err := utils.BindAndValid(c, &req); err != nil {
		response.Fail(c, err.Error())
		return
	}
	content := utils.FileGetContents(fmt.Sprintf("public/assets/shengshiqu/city-data-level%s.json", conv.String(req.Type)))
	c.String(http.StatusOK, content)
}
